<script setup>
import {computed, ref} from 'vue'
import { CScrollbar } from 'c-scrollbar'

// 定义父组件传来的参数
const props = defineProps({
  kind: { // 多个下拉列表的不同标识
    type: Number,
    required: false,
    default: 1
  },
  selList: { // 下拉列表数据
    type: Array,
    required: true,
    default: []
  },
  inboxed: { // 是否跟随界面滚动
    type: Number,
    required: true,
    default: false
  }
})

// emits 定义调用父级方法
const emits = defineEmits(['setVals'])

const retVal = ref([])
const selNames = ref([])

const selShow = ref(false)
// toggSelect 显示隐藏下拉框
const toggSelect = () => {
  if(selShow.value) {
    setTimeout(function() {
      emits('setVals', retVal.value)
    }, 200)
  }
  selShow.value = !selShow.value
}

// setVals 赋值
const setVals = (cur) => {
  if(cur.chked) { // 取消勾选
    let idx = retVal.value.findIndex(id => {
      if(id === cur.selId) {
        return true
      }
    })
    retVal.value.splice(idx, 1)
    selNames.value.splice(idx, 1)
  } else { // 选中
    retVal.value.push(cur)
    selNames.value.push(cur.selName + '[' + cur.selCode + ']')
  }
  cur.chked = !cur.chked
}

// schList 通过关键字筛选
const keywd = ref('')
const schList = computed(() => props.selList.filter((item) => item.selName.includes(keywd.value)))
</script>

<template>
  <div>
    <div :class="['sel-a', inboxed===1 ? 'sel-b' : '']">
      <input type="text" v-model="keywd" placeholder="请选择..." class="ipt" @click="toggSelect" @keyup="setSel" />
      <transition name="fade-mod" appear>
        <div class="sel-c" v-show="selShow" @mouseleave="toggSelect">
          <div class="sel-d">
            <c-scrollbar>
              <div :class="curSel.chked ? 'sel-e' : 'sel-f'" v-for="curSel in schList" :key="curSel.selId" @click="setVals(curSel)">
                <i :class="['iconfont', curSel.chked ? 'checkmark_square_fill chked' : 'app chk']"></i> {{curSel.selName}}
              </div>
            </c-scrollbar>
          </div>
        </div>
      </transition>
    </div>
    <div>{{selNames}}</div>
  </div>
</template>

<style scoped>
.sel-a {width: 240px; margin-right: 10px;}
.sel-b {position: relative;}
.sel-c {position: absolute; z-index: 4;}
.sel-d {min-width: 230px; height: 200px; overflow: hidden; background-color: #FFF; box-shadow: 0 2px 3px #999;}
.sel-e {height: 40px; line-height: 40px; padding: 0 20px; border-bottom: 1px solid #EEE; cursor: pointer; background-color: #e9f3fe;}
.sel-f {height: 40px; line-height: 40px; padding: 0 20px; border-bottom: 1px solid #EEE; cursor: pointer;}
.sel-f:hover {background-color: #e9f3fe;}
</style>
